import os
from webapp2 import RequestHandler, Route, WSGIApplication
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.webapp import template

def render(self, name, context, format=None):
  "Renders a template and writes it to the response. To keep DRY."
  
  context['user'] = users.get_current_user()
  
  if context['user']:
    context['user_action'] = 'logout'
    context['user_link'] = users.create_logout_url("/")
    
  else:
    context['user_action'] = 'login'
    context['user_link'] = users.create_login_url("/")
  
  #set default format
  if format is None:
    format = 'html'
    
  path = os.path.join(os.path.dirname(__file__), 'templates', name+'.'+format)
  out = template.render(path, context)
  self.response.out.write(out)
  
class OopsHandler(RequestHandler):
  def get(self):
    render(self, 'oops', {'stuff':'yeah'})

class Channel(db.Model):
  "A user created bucket where feed items will be thumbed up or down to create a matching system."
  name = db.StringProperty(required=True)
  created = db.DateTimeProperty(auto_now_add=True)
  creator = db.UserProperty(auto_current_user_add=True)

class ChannelHandler(RequestHandler):

  def get(self, key=None, format=None):
    c = {}
    if key is None:
      "Lists a user's Channels"
      c['title'] = "Channels"
      view = 'channel_list'
      c['channels'] = Channel.all().filter('creator =', users.get_current_user())
      
    else:
      "Displays details of a Channel"
      view = 'channel_details'
      c['channel'] = Channel.get(key)
      c['title'] = "Channel / "+c['channel'].name
      
    render(self, view, c, format)
    
  def post(self, key=None, format=None):
    "Create a new Channel"
    channel = Channel(name=self.request.get('name'))
    channel.put()
    self.redirect('/channels/'+str(channel.key()))
    
  def put(self, key, format=None):
    "Update an existing Channel"

# bootstrap
def main():
  app = WSGIApplication([
    (r'/', ChannelHandler),
    (r'/channels/?', ChannelHandler),
    Route(r'/channels/<key>', ChannelHandler),
  ], debug=True)
  app.error_handlers[404] = OopsHandler
  app.run()
  
if __name__ == '__main__':
  main()
